#include "Common.h"
#include "SystemV/AppLibSystemV_Msg.hpp"

#include <signal.h>

SINT32 gs32MsgId = -1;

void signal_deal(int signo)
{
    printf("catch signo:%d, exit process\n", signo);

    AppLibSystemV_MsgDestory(&gs32MsgId);

	exit(0);
}

void signal_register(void)
{
    signal(SIGHUP,  signal_deal);
    signal(SIGINT,  signal_deal);  //Ctrl + C
    signal(SIGQUIT, signal_deal);
    signal(SIGPIPE, signal_deal);
    signal(SIGALRM, signal_deal);
    signal(SIGTERM, signal_deal);
    signal(SIGSEGV, signal_deal);
    signal(SIGKILL, signal_deal);
}

int main(int argc, char **args)
{
	ULONG uRet = STAT_SUCCESS;
	CHAR szBuff[1024] = {0}; 
	APP_LIB_SYSTEM_V_MSG_s *pstMsg = (APP_LIB_SYSTEM_V_MSG_s *)szBuff;

	if (argc != 2)
	{
		printf("Usage: ./SystemV_Msg <Path>");
		return -1;
	}

	uRet = AppLibSystemV_MsgCreate(args[1], &gs32MsgId);
	if (uRet != STAT_SUCCESS)
	{
		printf("[%s %d] AppLibSystemV_MsgCreate ret=%lu\n", __func__, __LINE__, uRet);
		return -2;
	}

	while (1)
	{
		memset(szBuff, 0, sizeof(szBuff));
		pstMsg->usLen = sizeof(szBuff) -sizeof(pstMsg->lType);
		uRet = AppLibSystemV_MsgRecvWait(gs32MsgId, pstMsg);
		if (uRet != STAT_SUCCESS)
		{
			continue;
		}

		printf("[%s %d] Data %s\n", __func__, __LINE__, (char *)pstMsg->auData);
		if (strcmp((char *)pstMsg->auData, "quit") == 0)
		{
			break;
		}
	}

	AppLibSystemV_MsgDestory(&gs32MsgId);

	return 0;
}
